package com.xiaoxin.executor.batch.listener;

import com.xiaoxin.executor.domain.EtlLogJob;
import com.xiaoxin.executor.enums.EtlStatusEnum;
import com.xiaoxin.executor.service.EtlLogJobService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.batch.core.JobParameters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Job执行记录日志
 */
@Component
public class EtlLogListener implements JobExecutionListener {
    private static Logger logger = LogManager.getLogger(EtlLogListener.class);
    @Autowired
    private EtlLogJobService etlLogJobService;

    public void beforeJob(JobExecution jobExecution) {
        JobParameters jobParameters = jobExecution.getJobParameters();
        String jobName = jobExecution.getJobInstance().getJobName();
        EtlLogJob etlLogJob = new EtlLogJob();
        etlLogJob.setJobName(jobName);
        etlLogJob.setStatus(EtlStatusEnum.STATUS1.getCode());
        etlLogJob.setBeginTime(new Date());
        etlLogJob.setParams(jobParameters.toString());
        etlLogJobService.save(etlLogJob);
        jobExecution.getExecutionContext().put("etlLogJobId", etlLogJob.getId());

        String etlLogJobId = etlLogJob.getId();
        logger.info("Job {} start. ETL_LOG_JOB.ID:{}", jobName, etlLogJobId);
    }

    public void afterJob(JobExecution jobExecution) {
        String etlLogJobId = jobExecution.getExecutionContext().get("etlLogJobId") + "";
        EtlLogJob etlLogJob = new EtlLogJob();
        etlLogJob.setId(etlLogJobId);
        if (jobExecution.getStatus() == BatchStatus.COMPLETED) {
            etlLogJob.setStatus(EtlStatusEnum.STATUS2.getCode());
        } else {
            etlLogJob.setStatus(EtlStatusEnum.STATUS3.getCode());
        }
        etlLogJob.setEndTime(new Date());
        etlLogJobService.updateById(etlLogJob);

        String jobName = jobExecution.getJobInstance().getJobName();
        BatchStatus status = jobExecution.getStatus();
        logger.info("Job {} {}. ETL_LOG_JOB.ID:{}", jobName, status, etlLogJobId);
    }

}
